package com.bite.friend.manager;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.bit.common.redis.service.RedisService;
import com.bite.common.core.constants.CacheConstants;
import com.bite.common.core.constants.Constants;
import com.bite.common.core.enums.ExamListType;
import com.bite.common.core.utils.ThreadLocalUtil;
import com.bite.friend.domain.exam.Exam;
import com.bite.friend.domain.exam.dto.ExamQueryDTO;
import com.bite.friend.domain.exam.dto.ExamRankQueryDTO;
import com.bite.friend.domain.exam.vo.ExamVO;
import com.bite.friend.domain.user.UserExam;
import com.bite.friend.domain.user.vo.UserRankVO;
import com.bite.friend.mapper.exam.ExamMapper;
import com.bite.friend.mapper.user.UserExamMapper;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
public class ExamCacheManager {

    @Autowired
    private ExamMapper examMapper;

    @Autowired
    private UserExamMapper userExamMapper;

    @Autowired
    private RedisService redisService;

    // 保存用户的参赛信息
    public void saveUserExamCache(Long userId, Long examId) {
        String userExamKey = getUserExamKey(userId);
        redisService.leftPushForList(userExamKey, examId);
    }

    public Long getListSize(Integer examListType) {
        String examListKey = getExamListKey(examListType);
        return redisService.getListSize(examListKey);
    }

    public Long getRankListSize(Long examId) {
        return redisService.getListSize(getRankListKey(examId));
    }



    public List<ExamVO> getExamVOList(ExamQueryDTO examQueryDTO) {
        int start = (examQueryDTO.getPageNum() - 1) * examQueryDTO.getPageSize();
        int end = start + examQueryDTO.getPageSize() - 1; //下标需要 -1
        String examListKey = getExamListKey(examQueryDTO.getType());
        List<Long> examIdList = redisService.getCacheListByRange(examListKey, start, end, Long.class);
        List<ExamVO> examVOList = assembleExamVOList(examIdList);
        if (CollectionUtil.isEmpty(examVOList)) {
            refreshCache(examQueryDTO.getType());
            if (ExamListType.USER_EXAM_LIST.getValue().equals(examQueryDTO.getType())) {
                // 已经刷新过缓存了
                examIdList = getUserEnterExam();
                examVOList = assembleExamVOList(examIdList);
            } else {
                //说明redis中数据可能有问题 从数据库中查数据并且重新刷新缓存
                examVOList = getExamListByDB(examQueryDTO); //从数据库中获取数据
            }
//            //说明redis中数据可能有问题 从数据库中查数据并且重新刷新缓存
//            examVOList = getExamListByDB(examQueryDTO); //从数据库中获取数据
//            refreshCache(examQueryDTO.getType());
        }
        return examVOList;
    }

    // 获取到用户已经报名的
    public List<Long> getUserEnterExam() {
        return getUserEnterExam(getUserId());
    }

    public List<Long> getUserEnterExam(Long userId) {
        List<Long> userEnterExam = redisService.getCacheListByRange(getUserExamKey(userId), 0, -1, Long.class);
        if (CollectionUtil.isEmpty(userEnterExam)) {
            userEnterExam = userExamMapper.selectList(new LambdaQueryWrapper<UserExam>()
                            .select(UserExam::getExamId)
                    .eq(UserExam::getUserId, userId)).stream().map(UserExam::getExamId).toList();
            refreshCache(ExamListType.USER_EXAM_LIST.getValue());
        }
        return userEnterExam;
    }

    //刷新缓存逻辑
    public void refreshCache(Integer examListType) {
        List<Exam> examList = new ArrayList<>();
        if (ExamListType.EXAM_UN_FINISH_LIST.getValue().equals(examListType)) {
            //查询未完赛的竞赛列表
            examList = examMapper.selectList(new LambdaQueryWrapper<Exam>()
                    .select(Exam::getExamId, Exam::getTitle, Exam::getStartTime, Exam::getEndTime)
                    .gt(Exam::getEndTime, LocalDateTime.now())
                    .eq(Exam::getStatus, Constants.TRUE)
                    .orderByDesc(Exam::getCreateTime));
        } else if (ExamListType.EXAM_FINISH_LIST.getValue().equals(examListType)) {
            //查询历史竞赛
            examList = examMapper.selectList(new LambdaQueryWrapper<Exam>()
                    .select(Exam::getExamId, Exam::getTitle, Exam::getStartTime, Exam::getEndTime)
                    .le(Exam::getEndTime, LocalDateTime.now())
                    .eq(Exam::getStatus, Constants.TRUE)
                    .orderByDesc(Exam::getCreateTime));
        } else if (ExamListType.USER_EXAM_LIST.getValue().equals(examListType)) {
            //查询用户参加的竞赛
            examList = userExamMapper.selectUserExamList(getUserId());
        }
        if (CollectionUtil.isEmpty(examList)) {
            return;
        }

        Map<String, Exam> examMap = new HashMap<>();
        List<Long> examIdList = new ArrayList<>();
        for (Exam exam : examList) {
            examMap.put(getDetailKey(exam.getExamId()), exam);
            examIdList.add(exam.getExamId());
        }
        redisService.multiSet(examMap);  //刷新详情缓存
        redisService.deleteObject(getExamListKey(examListType));
        redisService.rightPushAll(getExamListKey(examListType), examIdList);      //刷新列表缓存
    }


    public void refreshRankListCache(Long examId) {
        List<UserRankVO> userExamList = userExamMapper.selectList(new LambdaQueryWrapper<UserExam>()
                .select(UserExam::getUserId, UserExam::getScore, UserExam::getUserRank)
                .eq(UserExam::getExamId, examId)
                .orderByAsc(UserExam::getUserRank)
        ).stream().map(userExam -> {
            UserRankVO userRankVO = new UserRankVO();
            BeanUtil.copyProperties(userExam, userRankVO);
            return userRankVO;
        }).toList();
        if (CollectionUtil.isEmpty(userExamList)) return;
        redisService.rightPushAll(getRankListKey(examId), userExamList);
    }

    private List<ExamVO> getExamListByDB(ExamQueryDTO examQueryDTO) {
        PageHelper.startPage(examQueryDTO.getPageNum(), examQueryDTO.getPageSize());
        //查询C端的竞赛列表
        return examMapper.list(examQueryDTO);
    }


    public List<UserRankVO> getRankVOList(ExamRankQueryDTO examRankQueryDTO) {
        String rankListKey = getRankListKey(examRankQueryDTO.getExamId());
        int start = (examRankQueryDTO.getPageNum() - 1) * examRankQueryDTO.getPageSize();
        int end = start + examRankQueryDTO.getPageSize() - 1; //下标需要 -1
        List<UserRankVO> userRankCacheList = redisService.getCacheListByRange(rankListKey, start, end, UserRankVO.class);
        if (CollectionUtil.isEmpty(userRankCacheList)) return null;
        return userRankCacheList;
    }

    private List<ExamVO> assembleExamVOList(List<Long> examIdList) {
        if (CollectionUtil.isEmpty(examIdList)) {
            //说明redis当中没数据 从数据库中查数据并且重新刷新缓存
            return null;
        }
        //拼接redis当中key的方法 并且将拼接好的key存储到一个list中
        List<String> detailKeyList = new ArrayList<>();
        for (Long examId : examIdList) {
            detailKeyList.add(getDetailKey(examId));
        }
        List<ExamVO> examVOList = redisService.multiGet(detailKeyList, ExamVO.class);
        CollUtil.removeNull(examVOList);
        if (CollectionUtil.isEmpty(examVOList) || examVOList.size() != examIdList.size()) {
            //说明redis中数据有问题 从数据库中查数据并且重新刷新缓存
            return null;
        }
        return examVOList;
    }

    private String getExamListKey(Integer examListType) {
        if (ExamListType.EXAM_UN_FINISH_LIST.getValue().equals(examListType)) {
            return CacheConstants.EXAM_UNFINISHED_LIST;
        } else if (ExamListType.EXAM_FINISH_LIST.getValue().equals(examListType)) {
            return CacheConstants.EXAM_FINISHED_LIST;
        } else if (ExamListType.USER_EXAM_LIST.getValue().equals(examListType)) {
            return CacheConstants.USER_EXAM_LIST + getUserId();
        }
        return "";
    }

    private String getDetailKey(Long examId) {
        return CacheConstants.EXAM_DETAIL + examId;
    }

    private String getUserExamKey(Long userId) {
        return CacheConstants.USER_EXAM_LIST + userId;
    }

    private String getRankListKey(Long examId) {
        return CacheConstants.EXAM_RANK_LIST + examId;
    }

    private Long getUserId() {
        Long userId = null;
        try {
            userId = ThreadLocalUtil.get(Constants.THREAD_LOCAL_USER_ID, Long.class);
        } catch (Exception e) {

        }
        return userId;
    }
}
